<template>
  <div>
    <router-view />
  </div>
</template>

<script>
export default {
  data () {
    return {
      oldViewport: [],
      htmlFontSize: '',
      bodyBgColor: ''
    };
  },
  created () {
    this.setREM();
    this.setBodyStyle();
  },
  beforeDestroy () {
    this.resetMetaAndFontsize();
    this.resetBodyStyle();
  },
  methods: {
    // 设置REM
    setREM () {
      const num = 1 / window.devicePixelRatio;
      const html = document.getElementsByTagName('html')[0];
      const clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
      const fontNum = (clientWidth * 100 / 750) * window.devicePixelRatio;
      this.removeMeta(true);
      this.addMeta(num);
      this.htmlFontSize = html.style.fontSize;
      html.style.fontSize = fontNum + 'px';
    },
    // 移除meta, 如果 cacheMeta 为true,则缓存原有meta
    removeMeta (cacheMeta) {
      const domHead = document.getElementsByTagName('head')[0];
      for (let i = 0; i < domHead.children.length; i++) {
        const item = domHead.children[i];
        if (item.nodeName === 'META' && item.name === 'viewport') {
          if (cacheMeta) {
            this.oldViewport.push(item);
          }
          domHead.removeChild(item);
          i--;
        }
      }
    },
    // 复原meta及字体大小
    resetMetaAndFontsize () {
      this.removeMeta();
      const domHead = document.getElementsByTagName('head')[0];
      const html = document.getElementsByTagName('html')[0];
      html.style.fontSize = this.htmlFontSize + 'px';
      for (let i = 0; i < this.oldViewport.length; i++) {
        const item = this.oldViewport[i];
        domHead.appendChild(item);
      }
    },
    // 添加meta
    addMeta (num) {
      const domHead = document.getElementsByTagName('head')[0];
      const _meta = document.createElement('meta');
      _meta.name = 'viewport';
      _meta.content = `width=device-width,user-scalable=no,initial-scale=${num},minimum-scale=${num},maximum-scale=${num}`;
      domHead.appendChild(_meta);
    },
    setBodyStyle () {
      const body = document.getElementsByTagName('body')[0];
      this.bodyBgColor = body.style.backgroundColor;
      body.style.backgroundColor = '#fcfcfc';
    },
    resetBodyStyle () {
      const body = document.getElementsByTagName('body')[0];
      body.style.backgroundColor = this.bodyBgColor;
    }
  }
};
</script>
